

#include "tp_typedef.h"
#include "tp_log.h"
#include "tp_bitmap_factory.h"
#include "tp_image_png_decoder.h"

typedef struct _TpBitmapFactory
{
    int decoder_nr;
    TpImageDecoder* decoders[TP_MAX_IMAGE_DECODER];
}TpBitmapFactory;

static TpBitmapFactory g_bitmap_factory;

TpRet tp_bitmap_factory_add_decoder(TpImageDecoder* decoder);

void tp_bitmap_factory_init(void)
{
    int i = 0;

    for(; i < TP_MAX_IMAGE_DECODER; ++i)
    {
        g_bitmap_factory.decoders[i] = NULL;
    }
    g_bitmap_factory.decoder_nr = 0;

    tp_bitmap_factory_add_decoder(tp_image_png_decoder_create());

    return;
}

void tp_bitmap_factory_uninit(void)
{
    int i = 0;
    for(; i < g_bitmap_factory.decoder_nr; ++i)
    {
        tp_image_decoder_destroy(g_bitmap_factory.decoders[i]);
        g_bitmap_factory.decoders[i] = NULL;
    }
    g_bitmap_factory.decoder_nr = 0;

    return;
}

TpRet tp_bitmap_factory_add_decoder(TpImageDecoder* decoder)
{
    if(g_bitmap_factory.decoder_nr >= TP_MAX_IMAGE_DECODER)
    {
        tp_image_decoder_destroy(decoder);
        return TP_RET_FAIL;
    }

    g_bitmap_factory.decoders[g_bitmap_factory.decoder_nr] = decoder;
    g_bitmap_factory.decoder_nr++;

    return TP_RET_OK;
}

TpBitmap* tp_bitmap_factory_load(const char* file)
{
    int i = 0;
    TpImageDecoder* decoder = NULL;

    for(; i < g_bitmap_factory.decoder_nr; ++i)
    {
        decoder = g_bitmap_factory.decoders[i];
        if(tp_image_decoder_match(decoder, file) == TP_RET_OK)
        {
            return tp_image_decoder_decode(decoder, file);
        }
    }

    /* tp_loge("tp_bitmap_factory_load: no proper decoder found."); */

    return NULL;
}

